package org.kordakus.shoot.model.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.net.URL;

import org.apache.log4j.Logger;
import org.kordakus.shoot.model.ImageFile;

public final class ImageFileWriter
{

	private static final Logger	_logger	= Logger.getLogger(ImageFileWriter.class);

	private ImageFileWriter()
	{
	}

	public static void writeImageFile(ImageFile file, String path)
			throws WriteImageFileException
	{
		if (file == null || path == null)
		{
			throw new IllegalArgumentException();
		}

		try
		{
			URL url = ImageFileWriter.class.getResource(path);
			if (url != null)
			{
				writeImageFile(file, new File(url.toURI()));
			} else
			{
				writeImageFile(file, new File(path));
			}
		} catch (URISyntaxException e)
		{
			throw new WriteImageFileException(e.getMessage(), e);
		}
	}

	public static void writeImageFile(ImageFile file, File dst)
			throws WriteImageFileException
	{
		if (file == null || dst == null)
		{
			throw new IllegalArgumentException();
		}

		try
		{
			if (!dst.exists() || dst.isFile())
			{
				dst.createNewFile();
			}
			if (dst.isFile())
			{
				writeImageFile(file, new FileOutputStream(dst));
			}
		} catch (Exception e)
		{
			throw new WriteImageFileException(e.getMessage(), e);
		}

	}

	public static void writeImageFile(ImageFile file, OutputStream stream)
	{
		file.writeImage(stream);
	}
}
